package com.ymm.utils.email;

import com.ymm.domain.entity.MailSendInfo;
import org.springframework.stereotype.Component;

import javax.activation.DataHandler;
import javax.activation.FileDataSource;
import javax.mail.Address;
import javax.mail.Message;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.*;
import java.io.File;
import java.util.Properties;

/**
 * 邮箱发送器
 *
 * @author 椰咩咩咩
 * @since 2023-01-20 13:03:40
 */
@Component
public class MailSander {
    /**
     * 文件发送方法
     *
     * @param mailSendInfo
     */
    public void sendMail(MailSendInfo mailSendInfo) {
        try {
            //设置邮箱服务器的相关配置
            Properties props = new Properties();
            //设置邮箱服务器的主机名
            props.setProperty("mail.smtp.host", mailSendInfo.getHost());
            //设置邮箱服务器的端口
            props.setProperty("mail.smtp.post", mailSendInfo.getPort());
            // 设置邮箱服务器是否需要身份认证,true为需要身份认证
            props.setProperty("mail.smtp.auth", String.valueOf(mailSendInfo.isAuth()));
            //身份认证
            EmailAuthentication emailAuthentication = new EmailAuthentication(mailSendInfo.getUser(), mailSendInfo.getPwd());
            //创建session对象
            Session session = Session.getDefaultInstance(props, emailAuthentication);
            //开启debug
            session.setDebug(true);

            /**
             * 邮件内容
             */
            //创建message对象
            Message message = new MimeMessage(session);
            //设置发送地址
            Address from = new InternetAddress(mailSendInfo.getFromAddress());
            message.setFrom(from);
            //设置邮件主题
            message.setSubject(mailSendInfo.getSubject());
            //设置邮件发送时间
            message.setSentDate(mailSendInfo.getSendDate());
            //设置收件人
            //判断收件人集合是否为空,不为空将集合里面
            Address[] addresses = new Address[mailSendInfo.getToAddresses().size()];
            if (mailSendInfo.getToAddresses() != null && mailSendInfo.getToAddresses().size() > 0) {
                //遍历集合
                for (int i = 0; i < mailSendInfo.getToAddresses().size(); i++) {
                    Address address = new InternetAddress(mailSendInfo.getToAddresses().get(i));
                    addresses[i] = address;
                }
            }
            message.setRecipients(Message.RecipientType.TO, addresses);
            //创建对媒体对象容器
            MimeMultipart mimeMultipart = new MimeMultipart();
            //创建正文内容
            MimeBodyPart bodyPart = new MimeBodyPart();
            bodyPart.setContent(mailSendInfo.getContent(), "text/html;charset=utf-8");
            mimeMultipart.addBodyPart(bodyPart);
            //创建附件部分
            if (mailSendInfo.getAttachFileNames() != null && mailSendInfo.getAttachFileNames().size() > 0) {
                for (int i = 0; i < mailSendInfo.getAttachFileNames().size(); i++) {
                    File file = new File(mailSendInfo.getAttachFileNames().get(i));
                    //如果文件存在，创建MimeBodyPart
                    if (file.exists()) {
                        MimeBodyPart attachPart = new MimeBodyPart();
                        DataHandler df = new DataHandler(new FileDataSource(file));
                        attachPart.setDataHandler(df);
                        //设置附件名，并解决乱码问题,通过MimeUtility.encodeText()解决
                        attachPart.setFileName(MimeUtility.encodeText(df.getName()));
                        mimeMultipart.addBodyPart(attachPart);
                    }
                }
            }
            //将多媒体容器添加到邮件当中
            message.setContent(mimeMultipart);
            //发送邮件
            Transport.send(message);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
